<template>
  <view style="width: 100%; min-height: 100vh;">
    <view style="width: 100%;">
      <view style="width: 100%; padding: 0 60upx;">
        <view class="flex justify-between align-center"
              style="width: 100%; height: 96upx; border-bottom: 2upx solid #F8F8F8;">
          <view style="font-size: 26upx; color: #333333;">头像</view>
          <view class="flex justify-end align-center" @click="handleUploadAvatar()" style="width: 50%;">
            <image :src="avatar || 'http://twst.isart.me/o_1ej1tutmv1isaddsc61mh01csg9.png'" mode="aspectFill"
                   style="width: 56upx; height: 56upx; border-radius: 50%; margin-right: 20upx;"></image>
            <image src="/static/icon/icon_more@2x.png" style="width: 30upx; height: 30upx;"></image>
          </view>
        </view>
        <view class="flex justify-between align-center"
              style="width: 100%; height: 96upx; border-bottom: 2upx solid #F8F8F8;">
          <view style="font-size: 26upx; color: #333333;">昵称</view>
          <view class="flex align-center">
            <input type="text" v-model="nick_name" placeholder="未填写" placeholder-style="color: #999999;"
                   style="text-align: right; font-size: 28upx;" maxlength="8">
          </view>
        </view>
        <view class="flex justify-between align-center sex-box">
          <view class="sex-name">性别</view>
          <view class="flex justify-end align-center sex-picker-box">
            <picker @change="handleChangeSex" :value="sex_index" :range="sex_array" class="picker-style flex align-center justify-end">
              <view class="uni-input">{{ sex_array[sex_index] }}</view>
              <image src="/static/icon/icon_more@2x.png" class="sex-picker-icon"></image>
            </picker>
          </view>
        </view>
        <view class="flex justify-between align-center sex-box">
          <view style="font-size: 26upx; color: #333333;">生日</view>
          <view class="flex justify-end align-center" style="width: 90%; font-size: 26upx;">
            <picker mode="date" :value="birthday" start="1900-01-01" :end="formatDate()" @change="handleChangeBirthday"
                    fields="day" class="picker-style flex align-center justify-end">
              <view class="picker">
                {{ birthday }}
              </view>
              <image src="/static/icon/icon_more@2x.png" class="sex-picker-icon"></image>
            </picker>
          </view>
        </view>
      </view>
      <view style="width: 100%; height: 20upx; background-color: #F8F8F8;"></view>
      <view style="width: 100%; padding: 0 60upx; margin-bottom: 200upx;">
        <view class="flex justify-between align-center"
              style="width: 100%; height: 96upx; border-bottom: 2upx solid #F8F8F8;">
          <view style="font-size: 26upx; color: #333333;">电话号</view>
          <view class="flex align-center">
            <input type="number" v-model="phonenum" placeholder="未填写" disabled="true" maxlength="11"
                   placeholder-style="color: #999999;" style="text-align: right; font-size: 28upx;">
          </view>
        </view>
        <view class="flex justify-between align-center"
              style="width: 100%; height: 96upx; border-bottom: 2upx solid #F8F8F8;">
          <view style="font-size: 26upx; color: #333333;">签名</view>
          <view class="flex align-center" style="width: 88%;">
            <input type="text" v-model="sign" placeholder="未填写" placeholder-style="color: #999999;"
                   style="text-align: right; font-size: 28upx; width: 100%;">
          </view>
        </view>
        <view class="flex justify-between align-center sex-box">
          <view style="font-size: 26upx; color: #333333;">地区</view>
          <view class="flex justify-end align-center" style="width: 80%; font-size: 26upx;">
            <picker mode="multiSelector" :value="city_array_index" range-key="city_name" :range="city_array"
                    @columnchange="handleColumnChangeCity" class="picker-style flex align-center justify-end">
              <view class="picker" style="font-size: 28upx;">
                {{ address }}
              </view>
              <image src="/static/icon/icon_more@2x.png" class="sex-picker-icon"></image>
            </picker>
          </view>
        </view>
        <view class="flex justify-between align-center"
              style="width: 100%; height: 96upx; border-bottom: 2upx solid #F8F8F8;">
          <view style="font-size: 26upx; color: #333333;">职位</view>
          <view class="flex align-center">
            <input type="text" v-model="industry" placeholder="未填写" placeholder-style="color: #999999;"
                   style="text-align: right; font-size: 28upx;">
          </view>
        </view>
      </view>
      <view style="width: 100%; padding: 0 76upx;">
        <view @click="handleSaveMyData" class="flex align-center justify-center"
              style="width: 596upx; height: 80upx; margin-bottom: 30upx; background-color: #E52718; color: white; font-size: 28upx; border-radius: 40upx;">
          保存信息
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {chooseImage, getQiniuToken} from "utils/wxUtil";
import {accountUser_getById, provinceCity_getListByProvince} from "api/my/my"
import {accountUser_editInfo} from "api/login/login";
import {debounce} from "utils/wxUtil";

export default {
  data() {
    return {
      sex_array: ['请选择', '男', '女'],
      province_index: 0,
      province: '', //省
      city: '', //市
      area: '', //区
      city_index: 0,
      country_index: 0,
      city_array_index: [0, 0, 0], //选中城市位置标识
      city_array: [
        [{
          city_name: '请选择',
          city_id: '',
          city_level: ''
        }],
        [{
          city_name: '请选择',
          city_id: '',
          city_level: ''
        }],
        [{
          city_name: '请选择',
          city_id: '',
          city_level: ''
        }]
      ], //三联省市区
      address: '', //地址
      sex_index: 0,
      birthday: '', //生日
      phonenum: '', //电话号
      endDate: new Date(),
      nick_name: '',
      avatar: '',
      user_information: {}, //用户信息
      industry: '', //职位
      sign: '', //签名
    }
  },
  methods: {
    formatDate() {
      const date = new Date();
      const YY = date.getFullYear() + '-';
      const MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      const DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
      return YY + MM + DD;
    },
    pageInit(account_user_id) {
      accountUser_getById({account_user_id}).then(res => {
        let {
          industry,
          nick_name,
          avatar,
          phonenum,
          gender,
          sign,
          birthday,
          address,
          province,
          city,
          area
        } = res.data;
        this.industry = industry;
        this.nick_name = nick_name;
        this.avatar = avatar;
        this.phonenum = phonenum;
        this.sex_index = gender;
        this.sign = sign;
        this.birthday = birthday;
        this.address = address;
        this.province_index = province;
        this.city_index = city;
        this.country_index = area;
      }).catch(err => {
        console.log(err)
      })
    },
    /**
     * @name 上传头像
     */
    handleUploadAvatar() {
      chooseImage(1).then(res => {
        // let upload_imgs = res.image_array;
        this.avatar = res.image_array[0];
      })
    },
    /**
     * @name 切换性别
     */
    handleChangeSex(e) {
      this.sex_index = e.target.value
    },
    /**
     * @name 切换生日
     */
    handleChangeBirthday(e) {
      this.birthday = e.detail.value;
    },
    /**
     * @name 切换城市列
     */
    handleColumnChangeCity(e) {
      this.city_array_index[e.detail.column] = e.detail.value
      switch (e.detail.column) {
        case 0:
          this.province_index = this.city_array[0][e.detail.value].city_id;
          this.province = this.city_array[0][e.detail.value].city_name;
          provinceCity_getListByProvince({
            parentId: this.city_array[0][e.detail.value].city_id
          }).then(res => {
            this.city_index = 0;
            this.country_index = 0;
            this.city_array = [
              this.city_array[0],
              [{
                city_name: '请选择',
                city_id: '',
                city_level: ''
              }],
              [{
                city_name: '请选择',
                city_id: '',
                city_level: ''
              }]
            ]
            res.data.forEach(item => {
              let city = {
                city_name: item.name,
                city_id: item.id,
                city_level: item.city_level
              }
              this.city_array[1].push(city);
            })
          })
          break;
        case 1:
          this.city_index = this.city_array[1][e.detail.value].city_id;
          this.city = this.city_array[1][e.detail.value].city_name;
          provinceCity_getListByProvince({
            parentId: this.city_array[1][e.detail.value].city_id
          }).then(res => {
            this.city_array = [
              this.city_array[0], this.city_array[1],
              [{
                city_name: '请选择',
                city_id: '',
                city_level: ''
              }]
            ]

            res.data.forEach(item => {
              let city = {
                city_name: item.name,
                city_id: item.id,
                city_level: item.city_level
              }
              this.city_array[2].push(city);
            })
          })
          break;
        case 2:
          this.country = this.city_array[2][e.detail.value].city_name;
          this.country_index = this.city_array[2][e.detail.value].city_id;
          break;
      }
      if (this.city_array[0].length > 0 && this.city_array[1].length > 0 && this.city_array[2].length > 0) {
        this.address = `${this.province || ''}${this.city || ''}${this.country || ''}`
      }
    },
    getCityData() {
      provinceCity_getListByProvince({
        parentId: 100000
      }).then(res => {
        console.log(res)
        res.data.forEach(item => {
          let city = {
            city_name: item.name,
            city_id: item.id,
            city_level: item.city_level
          }
          this.city_array[0].push(city);
        })
      }).catch(err => {
        console.log(JSON.stringify(err));
      })
    },
    /**
     * @name 保存信息
     */
    handleSaveMyData: debounce (function(){
      const validateToast = (vm, rules) => {
        return new Promise((resolve, reject) => {
          Object.keys(rules).forEach((key) => {
            const segments = key.split('.')
            const item = rules[key]
            item.forEach((ruleItem) => {
              const value = segments.reduce((total, item) => total && total[item], vm)
              // 必填
              if (ruleItem.required && !value) {
                reject(ruleItem.message)
              }
              // 正则
              if (ruleItem.pattern && !ruleItem.pattern.test(value)) {
                reject(ruleItem.message)
              }
            })
          })
          resolve(true)
        })
      }
      const validate_val_obj = {
        avatar: this.avatar,
        nick_name: this.nick_name,
        gender: this.sex_index,
        birthday: this.birthday,
        sign: this.sign,
        province: this.province_index,
        city: this.city_index,
        area: this.country_index,
        industry: this.industry,
        address: this.address,
      }
      const rules = {
        avatar: [
          {required: true, message: '请上传头像'},
          // { pattern: /^\d{1,}$/, message: 'xxx2' } // 正则校验
        ],
        nick_name: [{required: true, message: '请输入昵称'}],
        gender: [{required: true, message: '请选择性别'}],
        birthday: [{required: true, message: '请选择生日'}],
        sign: [{required: true, message: '请填写签名'}],
        province: [{required: false, message: '请选择地区'}],
        city: [{required: false, message: '请选择地区'}],
        area: [{required: false, message: '请选择地区'}],
        industry: [{required: false, message: '请填写职位'}],
        address: [{required: true, message: '请选择地区'}],
      }
      validateToast(validate_val_obj, rules).then(valid => {
        accountUser_editInfo(validate_val_obj).then(res => {
          uni.setStorageSync('user_info', res.data)
          uni.showToast({
            title: '保存成功',
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 500)
        }).catch(err => {
          console.log(err)
          uni.showToast({
            icon: 'none',
            title: err.msg,
          })
        })
      }).catch(err => {
        uni.showToast({
          icon: 'none',
          title: err,
        })
      })
    })
  },
  onLoad(e) {
    getQiniuToken();
    let user_info = uni.getStorageSync('user_info')
    if(!user_info){
      this.nick_name = e.name
    }
    this.getCityData()
    this.pageInit(user_info.id);
  }
}
</script>

<style scoped>
.sex-picker-icon{
  width: 30upx;
  height: 30upx;
  margin-left: 10upx;
}
.sex-picker-box{
  width: 90%;
  font-size: 26upx;
}
.sex-name{
  font-size: 26upx;
  color: #333333;
}
.sex-box{
  width: 100%;
  height: 96upx;
  border-bottom: 2upx solid #F8F8F8;
}
.picker-style {
  width: 90%;
  height: 96upx;
  line-height: 96upx;
  text-align: right;
}
</style>
